package com.offcn.pay.servicer.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.offcn.common.entity.Result;
import com.offcn.common.entity.StatusCode;
import com.offcn.pay.servicer.AliPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 阿里支付服务实现类
 *
 * @author 秋林
 * @date 2022/10/16 19:10:28
 */
@Service
public class AliPayServiceImpl implements AliPayService {
    @Autowired
    private AlipayClient alipayClient;

    @Value("${alipay.notify-url}")
    private String notifyUrl;

    /**
     * 生成支付宝支付二维码[方案一]
     *
     * @param out_trade_no 订单号
     * @param total_fee    金额(分)
     * @return {@link Map}
     */
    @Override
    public Map createNative(String out_trade_no, String total_fee) {
        HashMap map = new HashMap();

        //创建预下单请求对象
        AlipayTradePrecreateRequest precreateRequest = new AlipayTradePrecreateRequest();

        //转换下单金额按照(元)
        long total = Long.parseLong(total_fee);
        BigDecimal bigTotal = BigDecimal.valueOf(total);
        BigDecimal bg = BigDecimal.valueOf(100d);

        BigDecimal bigYuan = bigTotal.divide(bg);
        System.out.println("预下单金额：" + bigYuan.doubleValue());

        precreateRequest.setBizContent("{" +
                "    \"out_trade_no\":\"" + out_trade_no + "\"," +
                "    \"total_amount\":\"" + bigYuan.doubleValue() + "\"," +
                "    \"subject\":\"测试购买商品001\"," +
                "    \"store_id\":\"xa_001\"," +
                "    \"timeout_express\":\"90m\"}");//设置业务参数

        //发出下单业务请求
        try {
            AlipayTradePrecreateResponse response = alipayClient.execute(precreateRequest);
            //从响应对象读取响应结果
            String code = response.getCode();
            System.out.println("响应码：" + code);

            //全部的响应结果
            String body = response.getBody();
            System.out.println("返回结果：" + body);
            if (code.equals("10000")) {
                map.put("qrcode", response.getQrCode());
                map.put("out_trade_no", response.getOutTradeNo());
                map.put("total_fee", total_fee);

                System.out.println("获取二维码参数: " + response.getQrCode());
                System.out.println("订单号: " + response.getOutTradeNo());
                System.out.println("订单数量： " + total_fee);
            } else {
                System.out.println("预下单调用接口失败: " + body);
            }

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 查询支付状态
     *
     * @param out_trade_no 支付时传入的商户订单号
     * @return {@link Map}<{@link String},{@link String}>
     */
    @Override
    public Map<String, String> queryPayStatus(String out_trade_no) {
        HashMap<String, String> map = new HashMap<>();

        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "    \"out_trade_no\":\"" + out_trade_no + "\"," +
                "    \"trade_no\":\"\"}"); //设置业务参数
        //发出请求

        try {
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            String code = response.getCode();
            System.out.println("响应码： " + code);
            if (code.equals("10000")) {
                map.put("out_trade_no", out_trade_no);
                map.put("tradestatus", response.getTradeStatus());
                map.put("trade_no", response.getTradeNo());
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return map;
    }

    /**
     * 生成支付宝支付二维码[方案一]
     *
     * @param parameters 参数
     * @return {@link Map}
     */
    @Override
    public Map createNative(Map<String, String> parameters) {
        //创建阿里客户端请求对象
        HashMap<String, String> map = new HashMap<>();

        //创建预下单请求对象
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();

        //设置回调地址
        request.setNotifyUrl(notifyUrl);

        //设置预下单请求参数
        request.setBizContent("{" +
                "    \"out_trade_no\":\""+parameters.get("out_trade_no")+"\"," +
                "    \"body\":\"queue="+parameters.get("queue")+"&username="+parameters.get("username")+"&routingkey="+parameters.get("routingkey")+"&exchange="+parameters.get("exchange")+"\"," +
                "    \"total_amount\":\""+parameters.get("total_fee")+"\"," +
                "    \"subject\":\"测试购买商品001\"," +
                "    \"store_id\":\"xa_001\"," +
                "    \"timeout_express\":\"90m\"}");//设置业务参数

        //发出预下单业务请求
        try {
            AlipayTradePrecreateResponse response = alipayClient.execute(request);

            //从响应对象读取响应结果
            String code = response.getCode();
            System.out.println("响应码： "+ code);

            //全部响应结果
            String body = response.getBody();
            System.out.println("全部响应结果： " +body);

            if (code.equals("10000")){
                map.put("qrcode", response.getQrCode());
                map.put("out_trade_no", response.getOutTradeNo());
                map.put("total_fee", parameters.get("total_fee"));

                System.out.println("二维码参数: " + response.getQrCode());
                System.out.println("订单号: " +  response.getOutTradeNo());
                System.out.println("订单数量： " + parameters.get("total_fee"));
            }else {
                System.out.println("预下单接口调用失败:" + body);
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return map;
    }
}
